﻿using Furion.DependencyInjection;
using Furion.FriendlyException;
using HiSport.Application.System.Tenant.Dtos;
using HiSport.Core.Entity;
using HiSport.Core.Enum;
using Mapster;
using SqlSugar;
using Yitter.IdGenerator;

namespace HiSport.Application.System.Tenant.Service
{

    /// <summary>
    /// 租户
    /// </summary>
    public class TenantService : ITransient, ITenantService
    {
        public readonly ISqlSugarClient _dbContext;

        public TenantService(ISqlSugarClient dbContext)
        {
            _dbContext = dbContext;
        }

        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedList<SysTenant>> Page(PageTenantInput input)
        {
            RefAsync<int> total = 0;
            var list = await _dbContext.Queryable<SysTenant>()
                .ToPageListAsync(input.PageIndex, input.PageSize, total);

            return new PagedList<SysTenant>
            {
                Items = list,
                PageIndex = input.PageIndex,
                PageSize = input.PageSize,
                TotalCount = total
            };
        }


        /// <summary>
        /// 增加租户
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<bool> AddTenant(AddTenantInput input)
        {
            try
            {
                _dbContext.Ado.BeginTran();

                input.Id = YitIdHelper.NextId();

                var isExist = await _dbContext.Queryable<SysTenant>().Where(u => u.Name == input.Name).AnyAsync();
                 if (isExist) throw Oops.Oh(ErrorCodeEnum.D1300);

                 isExist = await _dbContext.Queryable<SysTenant>().Where(u => u.Account == input.Account).AnyAsync();
                if (isExist) throw Oops.Oh(ErrorCodeEnum.D1301);

                var tenant = input.Adapt<SysTenant>();
                var res=await _dbContext.Insertable(tenant).ExecuteCommandAsync();

                //初始化租户信息
               await InitNewTenant(tenant);

                _dbContext.Ado.CommitTran();
                return res > 0;
            }
            catch (Exception ex)
            {
                _dbContext.Ado.RollbackTran();
                throw Oops.Oh(ex);
            }


        }


        //public async Task<bool> UpdateTenant(UpdateTenantInput input)
        //{

        //}

        /// <summary>
        /// 新增租户初始化
        /// </summary>
        /// <param name="tenant"></param>
        private async Task InitNewTenant(SysTenant tenant)
        {
            var tenantId = tenant.Id;
            var tenantName = tenant.Name;

            //TODO  待完善
            // 初始化机构

            // 初始化角色

            

            // 初始化系统账号

            // 关联用户及角色

            // 关联租户组织机构和管理员用户
          
            // 默认租户管理员角色菜单集合
        }
    }
}
